export class DrawBG {
  //canvas上下文
  ctx: any;
  //canvas 元素
  canvas: any;
  //分辨率
  dpr = 1;
  windowHeight = 0;
  windowWidth = 0;
  bg: any;
  constructor() {}
  init(id: string) {
    const query = wx.createSelectorQuery();
    query
      .select(id)
      .fields({ node: true, size: true })
      .exec((res) => {
        console.log("canvas", id);
        this.canvas = res[0].node;
        this.ctx = this.canvas.getContext("2d");

        const sys = wx.getSystemInfoSync();
        this.windowHeight = sys.windowHeight;
        this.windowWidth = sys.windowWidth;

        this.dpr = sys.pixelRatio;
        this.canvas.width = res[0].width * this.dpr;
        this.canvas.height = res[0].height * this.dpr;

        this.requestFile()
      });
  }

  draw(){
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)

    this.ctx.drawImage(this.bg, 0, 0)

  }

  async requestFile() {
    let app = getApp();
    let imgUrl = app.globalData.dictMap.get("personalCenterBackgroundImage");
    this.bg = this.bg || (await this.download(imgUrl));
    
    this.draw()
  }

  //加载图片
  download(url: string) {
    return new Promise((resolve) => {
      const el = this.canvas.createImage();
      el.src = url;
      el.onload = (res: any) => {
        console.log("image", el);
        resolve(el);
      };
    });
  }
}
